<template>
	<view :style="{'--color': color}">
		<!-- 通用版 -->
		<view class="mask" @click="cancel">
			<view class="model" v-if="modelType == 99">
				<view class="titleTip">{{title}}</view>
				<view class="msgTip">{{msg}}</view>
				<view class="btns">
					<view class="btn-cancel" v-if='btn1' @click="cancel">{{btn1}}</view>
					<view class="btn-cancel" v-if='btn3' @click="backHome">{{btn3}}</view>
					<view class="btn-cancel" v-if='btn4' @click="other">{{btn4}}</view>
					<view class="btn-yes thmeBg"  @click="certain">{{btn2}}</view>
				</view>
			</view>
		</view>
		<Coupon v-if="CouponShow && couponArry" :couponArry="couponArry" @closeFunc="CouponShow=false"></Coupon>




		<u-popup :show="modelType == 2" round="10" :duration="200">
			<view class="ContentModel">
				<form @submit="Save">
					<view class="Model">
						<view class="headView m-bot30">
							<view class="view_img">
								<image :src="$imgUrls(headimg)" mode="aspectFill" class="headImg"></image>
								
								<!-- <view class="camera ">切换</view> -->
								<view class="iconfont icon-mn_shangchuantupian_fill size36 color_33 camera"></view>
							</view>
							<view class="size26 p-top14  text-center color_33">上传头像</view>
							<button open-type="chooseAvatar" type="default" class="AvatarBtn"
								@chooseavatar="bindchooseavatar"></button>
						</view>
					

						<view class="list">
							<text class="size28 color_33 bold500">昵称</text>
							<view class="rightView d-flex ">
								<input type="nickname" name="nickname" v-model="nickName"
									class="rightVal p-left30 p-right20 size26 color_33" placeholder="请输入您的昵称">
								<view class="d-flex a-center color_66 p-right20" 
								     @click="RandomList">
									<view class="iconfont icon-suijishushengcheng size36"></view>
									<text class="size22 m-left10">更换</text>
								</view>
							</view>
							
						</view>

                        
						
						<view class="row a-center m-top50 line40" :class="{'shake':shake}" v-if="agreementList.length">
							<view class="agress flexac m-right20" :class="{'okAgress':agree}" @click.stop="agree = !agree">
								<view class="iconfont icon-xiangxia white h7 m-top6"></view>
							</view>
							<text class="color_33 size22" @click.stop="agree = !agree">我已阅读并同意</text>
							<text class="color size22" 
							     v-for="item in agreementList" :key="item.id"
								 @click.stop="toDetails(item.id)">{{item.title}}</text>
							
						</view>
						
						<view class="row j-sb m-top60">
							<button class="login_btn bg33 flexac white size30 t-letter2" 
							     open-type="getPhoneNumber"
								@getphonenumber="getPhoneNumber" v-if="accredit">一键授权</button>
							<button class="login_btn bg33 flexac white size30 t-letter2"
								form-type="submit" v-else>一键授权</button>
							
							<view class="login_btn bgF2 flexac color_33 size30 t-letter2" @click.stop="cancel">取消
							</view>
						</view>
			
						
						
						

					</view>
				</form>
			</view>
		</u-popup>

	</view>
</template>


<script>
	import {
		mapState,
		mapMutations
	} from 'vuex'
	var that
	import API from '../../api/index.js'
	import Coupon from "../Coupons.vue"
	export default {
		/**
		 * goHome登录成功后是否返回首页  0不返回  1/null返回  
		 * btn1:取消按钮文字 
		 * btn2：确定按钮文字
		 * btn3：返回首页文字
		 * btn4：自定义
		 * msg：提示文字
		 * title: 标题
		 * **/
		props: ['type', 'title', 'msg', 'goHome', 'btn1', 'btn2', 'btn3', 'btn4', 'btn1_url', 'btn2_url', 'jump'],
		data() {
			return {
				// color: getApp().globalData.color,
				modelType: this.type, // 弹窗类型

				userinfo: '',
				noAuth: null, // 用户未授权 true已授权 false未授权

				imgUrl: this.imgUrl,
				CouponShow: false,
				couponArry: '',

				
				headimg: '',
				nickName: '',
				Phone: '',
				agree:false,
				agreementList:[],
				shake:false,
			}
		},
		components: {
			Coupon
		},
		watch: {
			type(e) {
				this.modelType = e
			}
		},
		created() {
			if(!this.regInfo) return;
			this.RandomList();
			this.agreements();
			
		
		},
		methods: {
			...mapMutations(['getUser']),
			
			cancel() { //取消
				this.$emit("cancelFunc")
			},
			certain() { //确定
				this.$emit("certain")
			},
			other() { //自定义
				this.$emit("otherFunc")
			},
			async getPhoneNumber(e) {
				let result = e.detail;
				console.log(result,'result');
				if (result.errMsg != 'getPhoneNumber:ok') return this.$Toast('未认证')
				const jscode = await this.getProvider();
				this.$showLoading('');
				this.$http.post({
					url: '/zzj_singleSaleApi/appletDecodePhone',
					data: {
						encryptedData: result.encryptedData,
						iv: result.iv,
						session_key: this.session_key,
						js_code:jscode
					}
				}).then(res => {
					this.$hideLoading();
					if (res.code != 200) return this.$Toast(res.msg);
					this.Phone = res.data;
					this.Login();
				})
			},
			
			async Login(){
				this.$showLoading('');
				const jscode = await this.getProvider();
				this.$http.post({
					url: '/zzj_singleSaleApi/appletLogin',
					data: {
						openid: this.openid,
						nickName: this.nickName,
						headimg: this.headimg,
						purePhoneNumber: this.Phone,
						share_v_id: this.share_v_id,
						js_code:jscode
					}
				}).then(res => {
					this.$hideLoading();
					if (res.code != 200) return this.$Toast(res.msg);
					let obj = {
						vid: res.v_id,
						userInfo: res.userInfo
					}
					uni.setStorageSync('vid', res.v_id);
					this.getUser(obj);
					this.cancel();
					this.$emit("loginSucceed")
					if(this.request.pid) this.bindRelation(res.v_id)
					this.maintainLog(res.v_id)
				})
			},
			
			bindchooseavatar(e) {
				let headimg = e.detail.avatarUrl;
				this.$common.uploadFiles(headimg).then(res => {
					if (res.errcode != '100') return this.$Toast('上传失败')
					let imgs = res.url.substring(22);
					this.headimg = imgs;
				})
			},

		  async	Save(e) {
				if (!this.headimg) return this.$Toast('头像不能为空!')
				if (!e.detail.value.nickname) return this.$Toast('昵称不能为空!')
				this.nickName = e.detail.value.nickname;
				if (!this.agree){
					this.$Toast('未同意协议');
					this.shake = true;
					setTimeout(()=>{
						this.shake = false;
					},300)
					return;
				} 
				const jscode = await this.getProvider();
				this.$showLoading('');
				this.$http.post({
					url: '/zzj_singleSaleApi/appletLogin',
					data: {
						openid: this.openid,
						nickName: this.nickName,
						headimg: this.headimg,
						purePhoneNumber: this.Phone,
						share_v_id: this.share_v_id,
						js_code:jscode
					}
				}).then(res => {
					this.$hideLoading();
					if (res.code != 200) return this.$Toast(res.msg);
					let obj = {
						vid: res.v_id,
						userInfo: res.userInfo
					}
					uni.setStorageSync('vid', res.v_id);
					this.getUser(obj);
					this.cancel();
					this.$emit("loginSucceed")
					if(this.request.pid) this.bindRelation(res.v_id)
					this.maintainLog(res.v_id)
				})
			},

			getProvider() {
				return new Promise((resolve,reject)=>{
					uni.getProvider({
						service: 'oauth',
						success: (res) => {
							uni.login({
								provider: res.provider[0],
								success: (req) => {
					                resolve(req.code)
								}
							})
						}
					})
				})
			},
			RandomList(){
				this.RandomArr(this.regInfo.imgList,'headimg');
				this.RandomArr(this.regInfo.nicknameList,'nickName');
			},
			RandomArr(array,name){
				let randomIndex = Math.floor(Math.random() * array.length);
				name == 'headimg'?this.headimg = array[randomIndex]:this.nickName = array[randomIndex];
				
			},
			
			agreements(){
				let agreeList = JSON.parse(JSON.stringify(this.regInfo.agreement));
				if(!agreeList.length) return;
				 agreeList.forEach((item,index)=>{
					 if(index != agreeList.length - 1){
					 	item.title = `《${item.title}》、`
					 }else{
					 	item.title = `《${item.title}》`
					 }
				})
				this.agreementList = agreeList;
			},
			toDetails(id){
				this.toUrl(`/otherPage/article/artDetail?artId=${id}`)
			},
			bindRelation(vid){ // 私域-绑定会员关系
				this.$http.post({
					url: '/PrivateSphereApi/bindPrivateRelation',
					data: {
						vid,
						pid: this.request.pid,
						way: this.request.w || 1
					}
				}).then(res=>{
					console.log(res)
				})
			},
			maintainLog(v_id){ // 维护口令使用记录
				let used_log_id = uni.getStorageSync('used_log_id')
				if(!used_log_id || used_log_id == 0) return
				this.$http.post({
					url: '/automaticTask/upDateUsedLog',
					data: {
						v_id,
						used_log_id
					}
				}).then(res=>{
					uni.removeStorageSync('used_log_id')
				})
			}

		},
		
		computed: {
			...mapState(['logo', 'openid', 'session_key', 'bid', 'share_v_id','color','regInfo','request']),
			accredit(){
				if(this.headimg && this.nickName && this.agree){
					return true;
				}else{
					return false;
				}
			}
		},
		
		watch:{
			agreementList:{
				 deep:true,
				 immediate:true,
				 handler(newVal,oldVal){
					 newVal.length?this.agree = false:this.agree = true;
				 }
				 
			}
			
		}
		
		
	}
</script>

<style scoped lang="scss">
	.shake {
	  animation: shake 0.3s;
	}
	@keyframes shake {
	  0% { transform: translateX(0); }
	  25% { transform: translateX(-10rpx); }
	  50% { transform: translateX(10rpx); }
	  75% { transform: translateX(-10rpx); }
	  100% { transform: translateX(0); }
	}
	.ContentModel {
		width: 100%;
		padding-bottom: constant(safe-area-inset-bottom);
		/*兼容 IOS<11.2*/
		padding-bottom: env(safe-area-inset-bottom);
		/*兼容 IOS>11.2*/
	}

	.Model {
		width: 100%;
		padding: 50rpx 50rpx 140rpx 50rpx;
		display: flex;
		flex-direction: column;
		align-items: center;

	}

	.headView {
		position: relative;
		padding: 10rpx 20rpx;
	}

	.headImg,
	.view_img {
		width: 140rpx;
		height: 140rpx;
		border-radius: 50%;
	}

	.view_img {
		box-shadow: 0 0 20rpx rgba(151, 151, 151, 0.3);
		position: relative;
	}

	.camera {
			position: absolute;
			right: 0rpx;
			bottom: 10rpx;
		}

	.AvatarBtn {
		position: absolute;
		width: 100%;
		height: 100%;
		left: 0;
		top: 0;
		z-index: 10;
		background-color: transparent;
	}

	.AvatarBtn::after {
		border: none;
	}

	.list {
		width: 100%;
		margin-top: 30rpx;
		display: flex;
		align-items: center;
	}

	.rightView {
		flex: 1;
		height: 80rpx;
		margin-left: 40rpx;
		background-color: #f2f2f2;
		border-radius: 40rpx;
		overflow: hidden;
	}
	.rightVal{
		flex: 1;
		height: 100%;
		background-color: #f2f2f2;
	}
	.gender {
		width: 50%;
		height: 100%;
		display: flex;
		justify-content: center;
		align-items: center;
		color: #b7b7b7;
	}

	.man {
		width: 50%;
		height: 100%;
		background-color: #6daff9;
		border-radius: 40rpx;
		color: #ffffff;
	}

	.woman {
		width: 50%;
		height: 100%;
		background-color: #ed6e86;
		border-radius: 40rpx;
		color: #ffffff;
	}

	

	.authBtn {
		width: 200rpx;
		height: 70rpx;
		background-color: #333333;
		border-radius: 35rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		position: relative;
		border: none;
	}

	.login_btn {
		width: 310rpx;
		height: 90rpx;
		padding:0;
		margin:0 0 30rpx 0;
		border-radius: 45rpx;
	}


	.agress{
		width:28rpx;
		height: 28rpx;
		border:1px solid #DEDEDE;
		border-radius: 50%;
	}
	.okAgress{
		border:1px solid var(--color);
		background-color: var(--color);
	}
	.icon-xiangxia{
		zoom: 0.8;
	}
	/* 弹窗样式 */
	.masks {
		position: fixed;
		left: 0;
		right: 0;
		top: 0;
		bottom: 0;
		background: rgba(0, 0, 0, .6);
		z-index: 1000;
	}

	.model {
		position: fixed;
		width: 654rpx;
		/* height: 320rpx; */
		left: 50%;
		top: 50%;
		border-radius: 32rpx;
		transform: translate(-50%, -50%);
		background: white;
		overflow: hidden;
		z-index: 999;
	}

	.titleTip {
		font-size: 36rpx;
		height: 111rpx;
		line-height: 160rpx;
		font-weight: bold;
		text-align: center;
	}

	.msgTip {
		font-size: 28rpx;
		color: #999999;
		text-align: center;
		padding: 30rpx 66rpx;
	}

	.btns {
		display: flex;
		justify-content: center;
		padding: 50rpx;
	}

	.btn-cancel {
		width: 260rpx;
		font-size: 30rpx;
		text-align: center;
		color: #969696;
		border: 1px solid #AFAFAF;
		border-radius: 68rpx;
		line-height: 68rpx;
		background: none;
		margin: 0 10rpx;
	}

	.btn-yes {
		width: 260rpx;
		font-size: 30rpx;
		color: white;
		text-align: center;
		border-radius: 68rpx;
		line-height: 68rpx;
		margin: 0 10rpx;
	}

	.logo {
		display: block;
		width: 222rpx;
		padding-top: 40rpx;
		margin: 0 auto;

		image {
			width: 100%;
		}
	}


	.mask {
		display: flex;
		align-items: center;
		justify-content: center;

		.model {
			background-color: #FFFFFF;
			border-radius: 12rpx;
			width: 600rpx;
			text-align: center;
			overflow: hidden;
			padding-top: 20rpx;

			.title {
				font-size: 32rpx;
				font-weight: bold;
				padding: 40rpx;
				color: #333333;
			}

			.info {
				font-size: 28rpx;
				padding: 20rpx 40rpx 40rpx;
				color: #666666;
			}

			.btns {
				.cancel {
					flex: 1;
					line-height: 88rpx;
					color: #999999;
					border-top: 1px solid #eeeeee;
				}

				.certain {
					flex: 1;
					line-height: 88rpx;
					background-color: #F8814E;
					color: white;
				}
			}
		}
	}
</style>